import os
import logging

from fastapi import FastAPI, Request, UploadFile, File
from starlette.responses import RedirectResponse

from .utils import OcrModel
from .data_model import *

LOG = logging.getLogger(__name__)
app = FastAPI(title='OCR文字识别接口')
ocr_model = OcrModel()
input_dir = os.getenv('INPUT_DIR', os.path.join(os.getcwd(), 'input'))
output_dir = os.getenv('OUTPUT_DIR', os.path.join(os.getcwd(), 'output'))


@app.get("/", summary="无index页面，将重定向到'CR文字识别接口'页面")
def index(request: Request):
    return RedirectResponse("{}docs".format(request.url))


@app.post("/ocr/delete", summary="删除input目录的所有文件，返回已删除的文件名和创建时间")
def delete():
    delete_files = os.listdir(input_dir)
    # os.path.getmtime() 函数是获取文件最后修改时间
    # os.path.getctime() 函数是获取文件最后创建时间
    delete_files = sorted(delete_files, key=lambda x: os.path.getmtime(os.path.join(input_dir, x)))
    result_dict = {}
    for filename in delete_files:
        path = os.path.join(input_dir, filename)
        result_dict[filename] = os.path.getmtime(path)
        os.remove(path)
    return result_dict


@app.post("/ocr/file", summary="选择图片文件进行OCR识别")
async def upload_file(file: UploadFile = File(...)):
    content = await file.read()
    file_type = file.content_type.split('/')[0]
    if file_type != 'image':
        return "only support image, but your is {}".format(file_type)
    result = ocr_model.get_text_from_bytes(content)
    return {"filename": file.filename, "result": result}


@app.put("/ocr/filename", summary="上传图片文件到容器内input文件夹")
async def create_upload_file(file: UploadFile = File(...)):
    content = await file.read()
    filepath = os.path.join(input_dir, file.filename)
    with open(filepath, 'wb') as f:
        f.write(content)
    return {"filename": file.filename}


@app.post("/ocr/filename", summary="对容器中input目录的图片文件名进行OCR识别")
def ocr_filename(filename: str):
    filepath = os.path.join(input_dir, filename)
    if not os.path.exists(filepath):
        return dict(msg='{} is not exist'.format(filepath))
    result = ocr_model.get_text_from_filepath(filepath)
    return {"filename": filename, "result": result}


@app.get("/ocr/filename", summary="获取容器中input目录中的文件")
def get_input_filename():
    all_files = os.listdir(input_dir)
    all_files = sorted(all_files, key=lambda x: os.path.getmtime(os.path.join(input_dir, x)))
    return all_files


@app.post("/ocr/base64", summary="对图片的base64编码值进行OCR识别(不要带data:image/png;base64前缀)")
def ocr_base64(ocr_base64_body: OcrBase64Body):
    result = ocr_model.get_text_from_base64(ocr_base64_body.base64)
    return {"filename": ocr_base64_body.filename, "result": result}
